/*********************************************************
          File Name:main.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Mon 27 Jul 2015 02:07:03 PM CST
**********************************************************/

#include "main.h"
#include "lock.h"

int main(int argc, char *argv[])
{
        size_t offset = 0;
        if(read_conf(&cfg, &offset) == -1)
        {
                printf("can't read\n");
                exit(1);
        }
        parse_cmd(cfg.pidfile, argc, argv);
        pid_t master;
        int timeout = 3;
#ifndef DBUG
        if(is_daemon == 0)
        {
                is_daemon = 1;
                if(isdaemon() == -1)
                {
                        fprintf(stderr, "%s", strerror(errno));
                        exit(1);
                }
        }
#ifdef __linux__
        prctl(PR_SET_NAME, "worker_master", NULL, NULL, NULL);
#endif
#endif
        master = getpid();
        pidfile(cfg.pidfile, &master, 'w');

        sigsetjmp(env, 1);                             // jump here
        if(restart == 1)
        {
                /*unlink(cfg.pidfile);
                execvp(argv[0], argv);                start a new instance*/
                offset = 0;
                read_conf(&cfg, &offset);
        }

        worker_num = cfg.process;
        pid_t local_workers[worker_num];
        workers = local_workers;

        do
        {
                listenfd = mysocket(SERVER, cfg.host, cfg.port, cfg.backlog, NULL);
                if(listenfd != -1)
                        break;
                sleep(timeout);
                timeout -= 1;
        }while(timeout >0);

        if(listenfd == -1)
                exit(1);
#ifdef __linux__
        acc_init();
#endif
        create_worker(cfg.process, cfg.thread, listenfd, workers);

        sig_manager();

        for(;;)
                pause();
}
